﻿<%@ WebHandler Language="C#" Class="dz" %>
using Common.Model;
using Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using System.IO;

using LitJson;
using System.Web.SessionState;
using ThoughtWorks.QRCode.Codec;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using Common.Wx;

/// <summary>
/// 文件上传处理页
/// </summary>
public class dz : IHttpHandler, IRequiresSessionState
{


    public static string APPID =WebConfigurationManager.AppSettings["APPID"];
    public static string APPSECRET =WebConfigurationManager.AppSettings["APPSECRET"];

    public void ProcessRequest(HttpContext context)
    {

        string openid = context.Request.Headers["X-ACCESS-USER"];//Header中的token
        string token=  context.Request.Headers["access_token"];//Header中的token  


        if (string.IsNullOrEmpty(openid))
        {
            HttpContext.Current.Response.Write("parameter error");
            return;
        }

        Entities bll = new Entities();


        var user = bll.User.FirstOrDefault(p=>p.UOpenID==openid);//全部.ToList();


        context.Response.Charset = "utf-8";
        context.Response.ContentType = "text/plain";

        //var img =context.Request["img"];
      
        var name=user.UNickName;
        var tjtoux ="http://wwx.50cms.com/Up/logo.png";
        if (!string.IsNullOrEmpty(user.UHeadImg))
        { 
              tjtoux =user.UHeadImg;
         }
        var tjname ="我为小熊代言";

        // var qcode =context.Request["qcode"];


        var qcode ="https://wwx.50cms.com:446/wx/?uid="+user.UID;

        string path = context.Server.MapPath("/Up/hbb2.jpg");

    
        WebClient client = new WebClient();
        byte[] bytes = client.DownloadData(tjtoux);
        MemoryStream ms88 = new MemoryStream(bytes);
        System.Drawing.Image copyImage = CirclePhoto(System.Drawing.Image.FromStream(ms88),124);


        //string GoodsImg =context.Server.MapPath(img);
        //WebClient clientGOOD = new WebClient();
        //byte[] bytesGoods = clientGOOD.DownloadData(GoodsImg);
        //MemoryStream msGOODS = new MemoryStream(bytesGoods);
        //System.Drawing.Image GoodsImage =System.Drawing.Image.FromStream(msGOODS);

        //初始化二维码生成工具
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
        qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
        qrCodeEncoder.QRCodeVersion = 0;
        qrCodeEncoder.QRCodeScale = 4;

        //将字符串生成二维码图片
        Bitmap image2 = qrCodeEncoder.Encode(qcode, Encoding.Default);


        Graphics EQgraphics = Graphics.FromImage(image2);

        EQgraphics.DrawImage(copyImage, new System.Drawing.Rectangle(45,45, 30, 30), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
        EQgraphics.Dispose();     //推荐人头像


        System.Drawing.Image image;
        image = System.Drawing.Image.FromFile(path);
        Graphics graphics = Graphics.FromImage(image);
        //加水印

        StringFormat drawFormat = new StringFormat();
        drawFormat.Alignment = StringAlignment.Near;

        StringFormat drawFormatCenter = new StringFormat();
        drawFormatCenter.Alignment = StringAlignment.Center;

        // Create rectangle for drawing.
        float x = 640;
        float y = 1136;
        float width = 640;
        float height = 1136;
        RectangleF drawRect = new RectangleF(x, y, width, height);

        // Draw rectangle to screen.
        Pen blackPen = new Pen(Color.Empty);
        graphics.DrawRectangle(blackPen, x, y, width, height);

        int imgwidth = 750;
        // Draw string to screen.
        // graphics.DrawString(title, new Font("黑体", 25), Brushes.Black, new Rectangle(0,30,imgwidth,25),drawFormatCenter);//"其他联系方式" 

        //  graphics.DrawImage(GoodsImage, new Rectangle(30, 95, 580, 580)); //缩放挥着Image到指定的rect

        // graphics.DrawImage(GoodsImage, new Rectangle(0, 50,imgwidth-20,GoodsImage.Height*(GoodsImage.Width/imgwidth)), 0, 0, imgwidth-20, GoodsImage.Height*(GoodsImage.Width/imgwidth), System.Drawing.GraphicsUnit.Pixel);
        //第一个image调图片位置，“-”的数字越小越往右、下，第二个image调整图大小，“+”调大





        //二维码
        graphics.DrawImage(image2, new System.Drawing.Rectangle(650, 320, image2.Width, image2.Height));//第一个image调图片位置，“-”的数字越小越往右、下，第二个image调整图大小，“+”调大






        graphics.DrawString(name, new Font("微软雅黑", 25), Brushes.White,620,460,drawFormat);//"姓1111名"   
        graphics.DrawString(tjname, new Font("微软雅黑", 25), Brushes.White,620,500,drawFormat);//"姓111111名"   


        //Brushes.Black不支持rgb,十六进制定义颜色，new System.Drawing.SolidBrush(Color.FromArgb(r,g,b))支持rgb定义颜色
        //释放画布
        graphics.Dispose();


        //设置输出的图片格式
        context.Response.ContentType = "image/jepg";


        //  context.Response.End();
        var  imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
        //获取相对于应用的基目录创建目录
        string imgPath = System.Web.Hosting.HostingEnvironment.MapPath("/image/");//System.AppDomain.CurrentDomain.baxxxxseDirectory + path;     //通过此对象获取文件名
        if (!Directory.Exists(imgPath))
        {
            Directory.CreateDirectory(imgPath);
        }
        image.Save(imgPath+imgName, ImageFormat.Jpeg);

        string  EqName = "EQ" + imgName;
        image2.Save(imgPath+EqName, ImageFormat.Jpeg);
        context.Response.Write(JsonConvert.SerializeObject(new { code=1,msg="ok",data="/image/"+imgName,EQ="/image/"+EqName}));



        return;
    }

    #region 生成小程序二维码
    /// <summary>
    /// 通过该接口生成的小程序码，永久有效，数量暂无限制。
    /// </summary>
    /// <param name="access_token"></param>
    /// <returns></returns>
    public static string CreateWxCode(string roomId, string page, string width,string picPath)
    {
        string ret = string.Empty, accesstoken = "", DataJson = "";
        try
        {
            ///获取token


            accesstoken = WxHelper.IsExistAccess_Token();
            string url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accesstoken;
            DataJson = "{";
            DataJson += string.Format("\"scene\":\"{0}\",", roomId);//所要传的参数用分看
            DataJson += string.Format("\"width\":\"{0}\",", width);
            DataJson += string.Format("\"page\":\"{0}\"", page);//扫码所要跳转的地址，根路径前不要填加'/'不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
            DataJson += "}";
            ret = CreateWeChatQrCode(url, DataJson, picPath);
        }
        catch (Exception e)
        {
            ret = e.Message;
        }
        return ret;//返回图片地址
    }


    /// <summary>
    /// 返回二维码图片
    /// </summary>
    /// <param name="url"></param>
    /// <param name="param"></param>
    /// <returns></returns>
    public static string CreateWeChatQrCode(string url, string param, string path)
    {

        string strURL =  url;
        HttpWebRequest request;
        string imgName = string.Empty;

        try
        {
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);


            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            string paraUrlCoded = param;
            //byte[] payload;
            byte[] payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();//返回图片数据流
            byte[] tt = StreamToBytes(s);//将数据流转为byte[]
            //在文件名前面加上时间，以防重名
            imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
            //获取相对于应用的基目录创建目录
            string imgPath = System.Web.Hosting.HostingEnvironment.MapPath(path);//System.AppDomain.CurrentDomain.baxxxxseDirectory + path;     //通过此对象获取文件名
            if (!Directory.Exists(imgPath))
            {
                Directory.CreateDirectory(imgPath);
            }
            System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(path + imgName), tt);//讲byte[]存储为图片


        }
        catch (Exception ex)
        {
        }
        return path + imgName;
    }


    /// <summary>
    /// 将数据流转为byte[]
    /// </summary>
    /// <param name="stream"></param>
    ///// <returns></returns>
    //public static byte[] StreamToBytes(Stream stream)
    //{
    //    List<byte> bytes = new List<byte>();
    //    int temp = stream.ReadByte();
    //    while (temp != -1)
    //    {
    //        bytes.Add((byte)temp);
    //        temp = stream.ReadByte();
    //    }
    //    return bytes.ToArray();
    //}
    #endregion


    public static string HttpGet(string Url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";


        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        return retString;
    }

    public static string CreateWxCode(string token)
    {
        string ret = string.Empty;
        try
        {
            string DataJson = string.Empty;
            string url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token;
            DataJson = "{";
            DataJson += string.Format("\"scene\":\"{0}\",", "所传参数内容1,所传参数内容2");//所要传的参数用,分看
            DataJson += string.Format("\"width\":\"{0}\",", 124);
            DataJson += string.Format("\"page\":\"{0}\",", "pages/index/index");//扫码所要跳转的地址，根路径前不要填加'/',不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
            DataJson += "\"line_color\":{";
            DataJson += string.Format("\"r\":\"{0}\",", "0");
            DataJson += string.Format("\"g\":\"{0}\",", "0");
            DataJson += string.Format("\"b\":\"{0}\"", "0");
            DataJson += "}";
            DataJson += "}";
            //DataJson的配置见小程序开发文档，B接口：https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html
            ret= PostMoths(url, DataJson);
            if(ret.Length>0)
            {
                //对图片进行存储操作，下次可直接调用你存储的图片，不用再调用接口
            }
        }
        catch (Exception e)
        { ret = e.Message; }
        return ret;//返回图片地址
    }




    //请求处理，返回二维码图片
    public static string  PostMoths(string url, string param)
    {
        string strURL = url;
        System.Net.HttpWebRequest request;
        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
        request.Method = "POST";
        request.ContentType = "application/json;charset=UTF-8";
        string paraUrlCoded = param;
        byte[] payload;
        payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
        request.ContentLength = payload.Length;
        Stream writer = request.GetRequestStream();
        writer.Write(payload, 0, payload.Length);
        writer.Close();
        System.Net.HttpWebResponse response;
        response = (System.Net.HttpWebResponse)request.GetResponse();
        System.IO.Stream s;
        s = response.GetResponseStream();//返回图片数据流
        byte[] tt = StreamToBytes(s);//将数据流转为byte[]

        //在文件名前面加上时间，以防重名
        string imgName = DateTime.Now.ToString("yyyyMMddhhmmss")+".jpg";
        //文件存储相对于当前应用目录的虚拟目录
        string path = "/image/";
        //获取相对于应用的基目录,创建目录
        string imgPath = System.AppDomain.CurrentDomain.BaseDirectory + path;     //通过此对象获取文件名

        System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(path+imgName), tt);//讲byte[]存储为图片
        return "/image/" + imgName;
    }
    ///将数据流转为byte[]
    public static byte[] StreamToBytes(Stream stream)
    {
        List<byte> bytes = new List<byte>();
        int temp = stream.ReadByte();
        while (temp != -1)
        {
            bytes.Add((byte)temp);
            temp = stream.ReadByte();
        }
        return bytes.ToArray();
    }


    /// <summary>
            /// 圆形图处理
            /// </summary>
            /// <param name="file">需要进行操作的图片</param>
            /// <param name="size">裁剪成格式（正方形size）</param>
            /// <returns></returns>
    public Bitmap CirclePhoto( System.Drawing.Image file, int size)
    {
        using ( System.Drawing.Image i = file)
        {
            Bitmap b = new Bitmap(size, size);
            using (Graphics g = Graphics.FromImage(b))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.DrawImage(i, 0, 0, b.Width, b.Height);
                int r = Math.Min(b.Width, b.Height) / 2;
                PointF c = new PointF(b.Width / 2.0F, b.Height / 2.0F);
                for (int h = 0; h < b.Height; h++)
                    for (int w = 0; w < b.Width; w++)
                        if ((int)Math.Pow(r, 2) < ((int)Math.Pow(w * 1.0 - c.X, 2) + (int)Math.Pow(h * 1.0 - c.Y, 2)))
                        {
                            b.SetPixel(w, h, Color.Transparent);
                        }
                //画背景色圆
                using (Pen p = new Pen(System.Drawing.SystemColors.Control))
                    g.DrawEllipse(p, 0, 0, b.Width, b.Height);
            }
            return b;
        }
    }



    public class UnlimitedQRCodeModel
    {

        public string scene { get; set; }

        public string page { get; set; }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}